var util = require('../../../utils/util.js')
const db = wx.cloud.database()
Page({
    data: {
        imgList: [],
        newsInfo: {
            istop: 0
        },
        userInfo: {},
        modal: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 判断用户是否授权，未授权返回授权页面
        var userInfo = wx.getStorageSync('userInfo');
        if (userInfo == "") {
            wx.navigateTo({
                url: '../../login/index',
            })
        } else {
            this.setData({
                userInfo: userInfo
            })
        }

    },
    input(e) {
        this.setData({
            password: e.detail.value
        })
    },
    hide() {
        this.setData({
            modal: false
        })
    },
    login() {
        let newsInfo = this.data.newsInfo
        if (this.data.password == 'sdpt1') {
            newsInfo.istop = 1
        } else {
            newsInfo.istop = 0
        }
        this.hide();
        this.setData({
            newsInfo: newsInfo
        })
    },

    onClick(e) {
        this.setData({
            modal: true
        })

    },

    // 置顶功能实现
    switchChange: function (e) {
        let newsInfo = this.data.newsInfo
        if (e.detail.value == true) {
            this.onClick()
        }
        // this.setData({
        //     newsInfo: newsInfo
        // })
    },

    // 更新话题数据
    updateValue: function (event) {
        let name = event.currentTarget.dataset.name;
        let newsInfo = this.data.newsInfo
        newsInfo[name] = event.detail.value
        this.setData({
            newsInfo: newsInfo
        })
    },

    ChooseImage() {
        wx.chooseImage({
            count: 3,
            sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], //从相册选择
            success: (res) => {
                let answer = res.tempFiles.every(item => { //限制上传图片大小为2M,所有图片少于2M才能上传
                    return item.size <= 7 * 1024 * 1024
                })
                if (answer) {
                    wx.showLoading({
                        title: '图片上传中...',
                    })
                    var time = util.formatTime(new Date());
                    var FilePaths = []
                    const temFilePaths = res.tempFilePaths
                    let promiseArr = [];
                    for (let i = 0; i < temFilePaths.length; i++) {
                        let promise = new Promise((resolve, reject) => {
                            var randstring = Math.floor(Math.random() * 1000000).toString() + '.png'
                            randstring = time + '-' + randstring
                            wx.cloud.uploadFile({
                                cloudPath: 'newsImages/' + randstring,
                                filePath: temFilePaths[i], // 文件路径
                                success: res => {
                                    //get resource ID
                                    console.log(res.fileID)
                                    FilePaths[i] = res.fileID
                                    resolve(res);
                                },
                                fail: err => {
                                    reject(err);
                                }
                            })
                        })
                        promiseArr.push(promise)
                    }
                    Promise.all(promiseArr).then((result) => {
                        if (this.data.imgList.length != 0) {
                            this.setData({
                                imgList: this.data.imgList.concat(FilePaths)
                            })

                            console.log(this.data.imgList.concat(FilePaths))
                        } else {
                            this.setData({
                                imgList: FilePaths
                            })
                        }
                        wx.hideLoading()
                    })
                } else {
                    wx.showModal({
                        content: '上传图片不能大于7M!',
                        showCancel: false,
                    });
                }
            }
        });
    },
    //全屏预览图片 预览的过程中用户可以进行保存图片、发送给朋友等操作
    ViewImage(e) {
        wx.previewImage({
            urls: this.data.imgList,
            current: e.currentTarget.dataset.url
        })
    },

    // 删除图片
    DelImg: function (event) {
        console.log(event.currentTarget.dataset.id)
        var id = event.currentTarget.dataset.id
        var imgList = this.data.imgList
        wx.cloud.deleteFile({
            fileList: [imgList[id]]
        }).then(res => {
            imgList.splice(id, 1)
            this.setData({
                imgList: imgList
            })
            console.log(res.fileList)
        }).catch(error => {
            // handle error
        })
    },

    // 提交表单给数据库
    submitform: function (event) {
        let newsInfo = this.data.newsInfo
        let userInfo = this.data.userInfo
        db.collection('news').add({
                // data 字段表示需新增的 JSON 数据
                data: {
                    title: newsInfo.title,
                    content: newsInfo.content,
                    publisher: userInfo.nickName,
                    imgUrl: this.data.imgList,
                    avatarUrl: userInfo.avatarUrl,
                    submitdate: db.serverDate(),
                    istop: newsInfo.istop,
                    comment: 0,
                    appreciate: 0,
                    view: 0
                }
            })
            .then(res => {
                wx.reLaunch({
                    url: '../topic/topic'
                })
            })
    },

    onShareAppMessage: function () {

    }
})